<script lang="tsx">
import { defineComponent, ref, watch, computed, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { $t } from '@vben/locales';
import BaseDrawer from '#/components/common/base-drawer.vue';
import { getMatchListApi, getGroupListApi } from '#/api/competition/registration-info';
import ImageListUpload from "#/components/common/image-list-upload.vue"
import Editor from '#/components/editor.vue';
import { createNewsApi, updateNewsApi, getNewsDetailApi } from '#/api/competition/news-mgr';
import FileVideo from './file-video.vue';
import FileDoc from './file-doc.vue';
import { Info } from '@vben/icons';

export default defineComponent({
  name: 'EditNewsMgr',
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
    newsInfo: {
      type: Object,
      default: () => ({}),
    }
  },
  emits: ['update:modelValue', 'update:confirm', 'cancel'],
  setup(props, { emit }) {
    const formRef = ref();
    const visible = ref(false);
    const loading = ref(false);
    const saveLoading = ref(false);
    const matchList = ref<Array<{ label: string; value: any }>>([]);
    const groupList = ref<Array<{ label: string; value: any }>>([]);
    const fileList = ref<Array<any>>([]);
    const uploadKey = ref(0); // 用于强制重新渲染上传组件
    const draft = ref('');
    const initFormData = () => {
      return {
        subject: '', // 资讯标题
        compId: '', // 所属大赛
        groupId: '', // 赛事组别
        module: 1, // 资讯类型
        initialViews: null, // 初始浏览次数
        initialVisitors: null, // 初始浏览人数
        fileType: 'doc', // 附件类型
        fileName: '', // 附件
        img: '', // 封面图片
        sort: null, // 列表排序
        content: '', // 资讯内容
      }
    }

    // 大赛名称下拉框
    const getMatchList = async () => {
      const res = await getMatchListApi();
      matchList.value = res.map((item: any) => ({
        label: item.matchName, // 使用 matchName 字段
        value: item.id
      }));
    }

    // 赛事组别下拉框
    const getGroupList = async () => {
      if (!localFormData.value.compId) {
        return [];
      }
      const params = {
        compId: localFormData.value.compId,
      }
      const res = await getGroupListApi(params);
      console.log('res', res);
      return res.data.map((item: any) => ({
        label: item.name,
        value: item.id
      }));
    }

    // 表单数据
    const localFormData = ref(initFormData() as Record<string, any>);
    // 基本信息表单配置
    const basicFormColumns = computed(() => [
      {
        prop: 'subject',
        label: $t('competition.newsMgr.newsTitle'),
        type: 'input',
        maxlength: 50,
        placeholder: $t('common.inputPhTxt', [$t('competition.newsMgr.newsTitle')]),
        required: true,
      },
      {
        prop: 'compId',
        label: $t('competition.newsMgr.belongCompetition'),
        type: 'select',
        placeholder: $t('common.selectPhTxt', [$t('competition.newsMgr.belongCompetition')]),
        required: true,
        get options() {
          return matchList.value;
        },
        onChange: async () => {
          localFormData.value.groupId = '';
          groupList.value = await getGroupList() || [];
        }
      },
      {
        prop: 'groupId',
        label: $t('competition.registrationInfo.groupName'),
        type: 'select',
        class: 'group-form-item',
        placeholder: $t('common.selectPhTxt', [$t('competition.registrationInfo.groupName')]),
        required: true,
        get options() {
          return groupList.value;
        },
        onChange: async () => {
          localFormData.value.trackId = '';
        }
      },
      {
        prop: 'module',
        label: $t('competition.newsMgr.newsType'),
        required: true,
        formItemProps: {
          style: {
            width: '100%',
            margin: '0 0 20px 0',
          },
        },
        render: () => {
          return (
            <div>
              <el-radio-group onChange={handleModuleChange} v-model={localFormData.value.module}>
                <el-radio-button value={1}>{$t('competition.newsMgr.module.1')}</el-radio-button>
                <el-radio-button value={2}>{$t('competition.newsMgr.module.2')}</el-radio-button>
              </el-radio-group>
            </div>
          )
        }
      },
      {
        prop: 'initialViews',
        label: $t('competition.newsMgr.initialViews'),
        placeholder: $t('common.inputPhTxt', [$t('competition.newsMgr.initialViews')]),
        render: () => {
          return (
            <el-input-number align="left" clearable controls={false} v-model={localFormData.value.initialViews} min={0} max={1000000} precision={0} placeholder={$t('common.inputPhTxt', [$t('competition.newsMgr.initialViews')])} />
          )
        }

      },
      {
        prop: 'initialVisitors',
        label: $t('competition.newsMgr.initialVisitors'),
        render: () => {
          return (
            <el-input-number align="left" clearable controls={false} v-model={localFormData.value.initialVisitors} min={0} max={1000000} precision={0} placeholder={$t('common.inputPhTxt', [$t('competition.newsMgr.initialVisitors')])} />
          )
        }
      },
      {
        prop: 'fileName',
        label: $t('competition.newsMgr.fileType'),
        required: true,
        get show() {
          return localFormData.value.module === 2;
        },
        formItemProps: {
          style: {
            width: '100%',
            margin: '0 0 20px 0',
          },
        },
        render: () => {
          return (
            <div>
              <el-radio-group onChange={handleFileTypeChange} v-model={localFormData.value.fileType}>
                <el-radio value={'doc'}>{$t('competition.newsMgr.fileType1')}</el-radio>
                <el-radio value={'vid'}>{$t('competition.newsMgr.fileType2')}</el-radio>
                <el-radio value={'zip'}>{$t('competition.newsMgr.fileType3')}</el-radio>
              </el-radio-group>
              {localFormData.value.fileType !== 'vid' && (
                <div class="w-full overflow-hidden">
                  <FileDoc uploadKey={uploadKey.value} fileType={localFormData.value.fileType} v-model={localFormData.value.fileName} fileInfo={localFormData.value.fileName} />
                </div>
              )}
              {localFormData.value.fileType === 'vid' && (
                <div class="w-full overflow-hidden">
                  <FileVideo uploadKey={uploadKey.value} fileType={localFormData.value.fileType} v-model={localFormData.value.fileName} fileInfo={localFormData.value.fileName} />
                </div>
              )}
            </div>
          )
        }
      },
      {
        prop: 'img',
        label: $t('competition.newsMgr.posterImage'),
        required: true,
        render: () => {
          return (
            <div class="w-full overflow-hidden">
              <div class="w-full text-[#AEAEAE] text-[12px] leading-[20px] mb-2">{$t('competition.newsMgr.posterImageTips')}</div>
              <ImageListUpload stemImages={coverImage.value} imgNumber={1} limitSizeImg={10}
                onUpdate:stemImages={handlePosterImageUpdate} />
            </div>
          )
        }
      },
      {
        prop: 'sort',
        label: $t('competition.newsMgr.sort'),
        render: () => {
          return (
            <el-input-number align="left" clearable controls={false} v-model={localFormData.value.sort} min={0} max={1000000} precision={0} placeholder={$t('common.inputPhTxt', [$t('competition.newsMgr.sort')])} />
          )
        }
      },
      {
        prop: 'content',
        get label() {
          return localFormData.value.module === 2 ? $t('competition.newsMgr.materialIntro') : $t('competition.newsMgr.content');
        },
        formItemProps: {
          style: {
            width: '100%',
            margin: '0 0 20px 0',
          },
        },
        render: () => {
          return (
            <div>
              {localFormData.value.module === 1 && (
                <Editor v-model={localFormData.value.content} />
              )}
              {localFormData.value.module === 2 && (
                <el-input maxlength={200} show-word-limit type="textarea" v-model={localFormData.value.content} placeholder={$t('common.inputPhTxt', [$t('competition.newsMgr.content')])} />
              )}
            </div>
          )
        }
      }
    ]);

    // 表单验证规则
    const formRules = {
      compId: [
        { required: true, message: $t('common.selectPhTxt', [$t('competition.registrationInfo.compName')]), trigger: 'change' }
      ],
      groupId: [
        { required: true, message: $t('common.selectPhTxt', [$t('competition.registrationInfo.groupName')]), trigger: 'change' }
      ],
      img: [
        { required: true, message: $t('competition.newsMgr.posterImageRequired'), trigger: 'change' }
      ],
      fileType: [
        {
          required: true,
          message: $t('common.selectPhTxt', [$t('competition.newsMgr.fileType')]),
          trigger: 'change',
          validator: (rule: any, value: any, callback: any) => {
            if (!value) {
              callback(new Error($t('common.selectPhTxt', [$t('competition.newsMgr.fileType')])));
            } else {
              callback();
            }
          }
        }
      ],
      fileName: [
        {
          required: true,
          message: $t('common.inputPhTxt', [$t('competition.newsMgr.fileUrl')]),
          trigger: 'change',
          validator: (rule: any, value: any, callback: any) => {
            if (localFormData.value.module === 2 && !value) {
              callback(new Error($t('common.inputPhTxt', [$t('competition.newsMgr.fileUrl')])));
            } else {
              callback();
            }
          }
        }
      ]
    };

    const coverImage = computed(() => {
      return localFormData.value.img ? [{ id: 'cover', path: localFormData.value.img }] : [];
    });

    // 监听 modelValue 变化
    watch(() => props.modelValue, (val) => {
      visible.value = val;
      if (val) {
        // 加载表单中大赛名称，赛事组别，所属赛题的option
        getMatchList();
        if (props.newsInfo.id) {
          loading.value = true;
          getNewsDetailApi(props.newsInfo.id).then((res: any) => {
            // 根据 initFormData 结构映射回显数据
            const mappedData = {
              subject: res.subject || '',
              compId: res.compId || '',
              groupId: res.groupId || '',
              module: +res.module || 1,
              initialViews: res.initialViews || null,
              initialVisitors: res.initialVisitors || null,
              fileType: res.fileType || 'doc',
              fileName: res.fileName || '',
              img: res.img || '',
              sort: res.sort || null,
              content: res.content || '',
            };
            localFormData.value = mappedData;
            draft.value = res.draft;
            // 如果有大赛ID，需要加载对应的组别列表
            if (mappedData.compId) {
              getGroupList().then((groups) => {
                groupList.value = groups || [];
              });
            }
          }).finally(() => {
            loading.value = false;
          });
        } else {
          initForm();
        }
      } else {
        initForm();
      }
    }, { deep: true });

    // 处理关闭
    const handleClose = () => {
      ElMessageBox.confirm($t('competition.newsMgr.confirmClose'), $t('common.tipTxt'), {
        confirmButtonText: $t('common.submitTxt'),
        cancelButtonText: $t('common.cancelTxt'),
        type: 'warning',
      }).then(() => {
        handleConfirmClose();
      }).catch(() => {
        console.log('cancel');
      });
    };

    const handleConfirmClose = () => {
        draft.value = '';
        initForm();
        emit('update:modelValue', false);
        emit('cancel');
    }

      // 处理确认
      const handleConfirm = async (type: string) => {
        if (!formRef.value) return;
        console.log('localFormData.value', localFormData.value);
        try {
          // 表单验证
          const valid = await new Promise((resolve) => {
            formRef.value.validate((isValid: boolean) => {
              resolve(isValid);
            });
          });
          if (!valid) {
            return;
          }
          // 验证封面图片是否上传
          if (!localFormData.value.img) {
            ElMessage.error($t('competition.newsMgr.posterImageRequired'));
            return;
          }

          // 验证资源文件是否上传（当资讯类型为材料时）
          if (localFormData.value.module === 2) {
            if (!localFormData.value.fileName) {
              ElMessage.error($t('competition.newsMgr.fileUrlRequired'));
              return;
            }
          }
          handleCreateNews(type);
        } catch (error) {
          console.error('error', error);
        }
      };

      const handleCreateNews = (type: string) => {
        type === 'save' ? saveLoading.value = true : loading.value = true;
        const params = {
          ...localFormData.value,
          publishStatus: type === 'push' ? true : (props.newsInfo.id ? props.newsInfo.publishStatus : false),
          draft: type === 'save' ? (draft.value || JSON.stringify(localFormData.value)) : ''
        }
        const API = props.newsInfo.id ? updateNewsApi({ ...params, id: props.newsInfo.id }) : createNewsApi(params);
        API.then((res: any) => {
          if (res) {
            ElMessage.success($t(type === 'save' ? (props.newsInfo.publishStatus === 'false' ? 'competition.newsMgr.updateSuccess' : 'competition.newsMgr.saveSuccess') : 'competition.newsMgr.createSuccess'));
            emit('update:confirm');
            handleConfirmClose();
          } else {
            ElMessage.error(res.message);
          }
        }).finally(() => {
          type === 'save' ? saveLoading.value = false : loading.value = false;
        });
      }


      // 更新表单数据
      const handleFormUpdate = (data: any) => {
        localFormData.value = data;
      };

      // 初始化表单数据
      const initForm = () => {
        localFormData.value = initFormData();
        fileList.value = [];
        uploadKey.value = 0;
      }

      // 处理封面图片上传
      const handlePosterImageUpdate = (data: any) => {
        localFormData.value.img = data[0]?.path || '';
      }

      const handleFileTypeChange = (value: any) => {
        // 重置文件相关数据
        localFormData.value.fileName = '';
        fileList.value = [];

        // 清除文件上传组件的验证状态
        if (formRef.value && formRef.value.clearValidate) {
          formRef.value.clearValidate('fileName');
        }

        // 强制重新渲染上传组件
        uploadKey.value += 1;
      }

      const handleEditDraft = () => {
        localFormData.value = JSON.parse(draft.value || '');
      }

      const handleDeleteDraft = () => {
        ElMessageBox.confirm($t('competition.newsMgr.confirmDeleteDraft'), $t('common.tipTxt'), {
          confirmButtonText: $t('common.submitTxt'),
          cancelButtonText: $t('common.cancelTxt'),
          type: 'warning',
        }).then(() => {
          draft.value = '';
          ElMessage.success($t('competition.newsMgr.deleteDraftSuccess'));
        }).catch(() => {
          return;
        });
      }

      const handleModuleChange = (value: any) => {
        localFormData.value.fileName = '';
        localFormData.value.content = '';
      }

      return () => (
        <BaseDrawer
          modelValue={visible.value}
          title={props.newsInfo.id ? $t('common.editTxt') : $t('common.newTxt')}
          onUpdate:modelValue={(val: boolean) => emit('update:modelValue', val)}
          showFooter={true}
          confirmText={loading.value ? $t('tenant.submitting') : $t('common.submitTxt', [''])}
          cancelText={$t('common.cancelTxt')}
          beforeClose={handleClose}
          v-slots={{
            footer: () => (
              <div class="dialog-footer">
                <el-button disabled={loading.value || saveLoading.value} onClick={handleClose}>{$t('common.cancelTxt')}</el-button>
                <el-button disabled={loading.value} loading={saveLoading.value} onClick={() => handleConfirm('save')}>{$t('common.saveTxt')}</el-button>
                <el-button disabled={saveLoading.value} type="primary" onClick={() => handleConfirm('push')} loading={loading.value} class="w-[80px]">{$t('common.pushTxt')}</el-button>
              </div>
            )
          }}
        >
          <div v-loading={loading.value} class="add-registration-info-container">
            {draft.value && (
              <div class="bg-[#E0ECF9] w-full text-[#AEAEAE] text-[12px] rounded-[4px] leading-[22px] mb-5 py-[10px] px-[16px] flex justify-between items-center">
                <div class="flex items-center">
                  <Info class="mr-2 text-[#0067D1]" />
                  <span class="text-[#191919]">{$t('competition.newsMgr.lastEditRecord')}</span>
                </div>
                <div>
                  <el-button link type="primary" onClick={handleEditDraft}>{$t('competition.newsMgr.editDraft')}</el-button>
                  <el-button link type="primary" onClick={handleDeleteDraft}>{$t('competition.newsMgr.deleteDraft')}</el-button>
                </div>
              </div>
            )}
            <div class="form-section">
              <div class="section-content">
                <base-form
                  ref={formRef}
                  columns={basicFormColumns.value}
                  modelValue={localFormData.value}
                  rules={formRules}
                  label-position="right"
                  label-width="110px"
                  inline={true}
                  onUpdate:modelValue={handleFormUpdate}
                />
              </div>
            </div>
          </div>
        </BaseDrawer>
      );
    }
  });
</script>

<style lang="scss" scoped>
.add-registration-info-container {
  .form-section {
    .section-content {
      :deep(.base-form-item) {
        margin-bottom: 20px;

        .el-form-item__content {
          width: 100%;
        }
      }

      // 设置宽度不为100%且排列在右边的表单项，margin-right为0
      :deep(.el-form-item:not([style*="width: 100%"])) {
        width: calc((100% - 32px)/2);

        &:nth-of-type(even) {
          margin-right: 0 !important;
        }
      }

      :deep(.el-input-number .el-input__inner) {
        text-align: left;
      }

      :deep(.el-form--inline .el-form-item) {
        vertical-align: top;
      }
    }
  }
}
</style>
